#!/bin/bash
# 原始音频文件为.raw
WORKDIR=$1

rawfilename="rawlist.txt"
nrawfilename="nrawlist.txt"
rawout="raw_out.txt"
wavout="wav_out.txt"
dir="dir.txt"

AUDIOCUT_SEED=10
RATE=16000

array=(5 10 15)

for SNR in ${array[*]}
do
  OUT_WORKDIR=${WORKDIR}_${SNR}dB_$3
  # 清除
  rm -rf $OUT_WORKDIR
  # 噪音文件
  NOISEFILE="noises/$2_${SNR}dB_noise_$3.wav"
  # 创建文件目录
  find ${WORKDIR}/* -type d > $dir
  sed -i "s|${WORKDIR}|${OUT_WORKDIR}|g" $dir
  while IFS= read -r filein <&1
  do
    mkdir -p $filein
  done 1<$dir
  echo "[ ${OUT_WORKDIR} ] 复制目录结构已完成，下一步生成rawlist nrawlist"

  find ${WORKDIR} -type f -iname '*.raw'| sort > $rawfilename
  
  sed "s|.raw|.noise.raw|g" $rawfilename > $nrawfilename

  sed "s|${WORKDIR}|${OUT_WORKDIR}|g" $rawfilename > $rawout
  sed 's/\.raw/.wav/g' $rawout > $wavout

  # # Adding noise
  if [ $RATE -eq 16000 ]; then
    ./filter_add_noise -i rawlist.txt -o nrawlist.txt -n $NOISEFILE -s $SNR -r $AUDIOCUT_SEED -u $RATE –e fant.log 
  else
    ./filter_add_noise -i rawlist.txt -o nrawlist.txt -n $NOISEFILE -s $SNR -r $AUDIOCUT_SEED –e fant.log
  fi
  echo "[ ${OUT_WORKDIR} ]合成噪音已完成，下一步：raw文件转wav文件"
  # Converting RAW files back to WAV files
  while IFS= read -r filein <&3 && IFS= read -r fileout <&4
  do
    # echo sox -e signed-integer -b 16 -r $RATE -c 1 "$filein" "$fileout"
    sox -e signed-integer -b 16 -r $RATE -c 1 "$filein" "$fileout"
  done 3<$nrawfilename 4<$wavout
  echo "[ ${OUT_WORKDIR} ]完成"
  # 删除数据源目录下所有带噪音的音频文件
  find ${WORKDIR} -name '*.noise.raw' -delete
done